#include "Encoder.h"

Encoder::Encoder(byte pinA, byte pinB, byte pinC) {
	_pinA = pinA;
	_pinB = pinB;
	_pinC = pinC;
	_delay = 100;
	pinMode(_pinA, INPUT);
	pinMode(_pinB, INPUT);
	pinMode(_pinC, INPUT);
}

void Encoder::setPulse( encoder_callback cb ) {
	callback = cb;
}

void Encoder::setButton( button_callback cb ) {
	btnCallback = cb;
}

void Encoder::begin() {


}

void Encoder::setDelay( int delay ) {

	_delay = delay;
}

void Encoder::poll() {
	a =  digitalRead(_pinA);
	b =  digitalRead(_pinB);
	c =  digitalRead(_pinC);

	_val = a + ( b << 1);
	_pulse = 2;
	if (_val != _pVal) {

	    if (_val == 1 && _pVal == 0)
	    	_pulse = 1;
	    if (_val == 2 && _pVal == 3)
		_pulse = 1;

	    if (_val == 1 && _pVal == 3)
		_pulse = 0;
    	    if (_val == 2 && _pVal == 0)
		_pulse = 0;  
	
	    if ( _pulse == 1) 
	    	(*callback)( true );
	    if ( _pulse == 0 )
		(*callback)( false );
		

	}

	if ( c != lastC ) 
	{
		lastMillis = millis();
	}
	if (( millis() - lastMillis) > _delay ) {
		if ( c == true ) {	
			lastMillis = millis();
			(*btnCallback)();

		}
	}
	lastC = c;
         _pVal = _val;
       

}